<?php
include_once "../init.inc.php";
include_once '../inc/header.php';
include_once "../class/pageNavigator.php";

  define("PERPAGE", 10);
  define("OFFSET", "offset");
  define("USE_SPHINX", TRUE);


?>
<script>
        function start(){
       basket = decodeURI($.cookie("basket")); 
               if (basket=='null') {basket = '';}
     var basketArray = basket.split(",");
     var links = $('a.addCart');
     
     links.each(function(index, elem) {
         var msgid = $(this).attr('id');
     //$(elem).html("=");
                            //здесь при первой загрузке страницы
                            for(var i=0; i<basketArray.length-1;i++) {
                                    goodsId = basketArray[i];
                                    if(goodsId == msgid)  // товар уже в корзине
                                    {
                                        //check = true;
                                        //delete basketArray[i];
                                        // break;
                                        //$(this).html("Del");
                                        $(this).html('<img class="imgcart" src="../images/cart_delete.png">Delete');
                                        $(this).removeClass();
                                        $(this).addClass("delCart");
                                    }
                                }
     
     
     //  console.log($(this).attr('id'));

     });
     }
     
     
 $(document).ready(function(){ 
    $(".searchInput").focus();
     start();
     
 
      //*********************************************************
     
      $('a.addCart, a.delCart').click(function(){
      data = $(this).attr('id');
      addCart(data);
        var val = $(this).text();
    //console.log(val);
    //здесь при нажатии на кнопку
                 if (val == "Delete"){
                    //$(this).html("Add");
                    $(this).html('<img class="imgcart" src="../images/cart_add.png">Add');
                    $(this).removeClass();
                    $(this).addClass("addCart");
                }else{
                  // $(this).html("Del"); 
                  $(this).html('<img class="imgcart" src="../images/cart_delete.png">Delete');
                  $(this).removeClass();
                  $(this).addClass("delCart");
                };
      return false;
       
     });

    function addCart(p1){
        
     //   alert(p1);
     var msgid;
       msgid = p1;  
        var basket = '';
        var check = false;
        var cnt = false;
        var basketRet;
     
     basket = decodeURI($.cookie("basket"));
     
       if (basket=='null') {basket = '';}
       
       basketArray = basket.split(",");
       for(var i=0; i<basketArray.length-1;i++) {
           goodsId = basketArray[i];
           if(goodsId == msgid || goodsId=="")   // ищем, не покупали ли мы этот товар ранее
           {
               check = true;
               delete basketArray[i];

              // break;
           }
       }
       
    if(!check){
          // basket+= msgid +  ',';
          basketArray += msgid + ',';
    }
     
    basketRet =  $.makeArray(basketArray);
        
        for(var i=0; i<basketRet.length-1;i++) {
          if (basketRet[i]=="" || !(basketRet[i])){
             basketRet.splice(i,1);
             i=0;
          }
          
      }
     
          basketRet = basketRet.join();
          
         
       


           $.cookie("basket", basketRet, {path: "/"});
     
     


    }

 
 } 
 ) 
    </script>
		



<form id="formsearch" action ="" method="get">
    <fieldset id="search-field">
    <!--<select name="cat" class ="searchSelect"> <?//echo getCat();?></select>-->
    <!--
    //убираем полнотекстовый поиск
    <select name="type" class ="searchSelect"> 
        <?php// if ($_GET['type']=='and'){ ?>
        <option value="or">OR</option>
        <option selected value="and">AND</option>
        <?php// }else { ?>
         <option selected value="or">OR</option>
         <option value="and">AND</option>
         <?php// } ?>
    </select>
    -->
    <input name="search" value="<?=@$_REQUEST['search']?>" class ="searchInput input-xlarge" type ="text"/>
   <?php // <input type="submit" class ="searchbtn btn btn-medium btn-primary mybtn" value="Search"/><br /> ?>
    <a  class="btn btn-primary" href="#" onclick="document.forms['formsearch'].submit(); return false;"><i class="icon-search icon-white"></i>&nbsp;Search</a><br />
    <div id="under"><input id="checktitle" name="checktitle" type="checkbox"  value="1" /><span class="text-info">&nbsp;Search only in titles</span></div>
   
    </fieldset>
</form>

<?php
//****************************************************************************************

if ($_GET['search']){
    
    
   
    // тестовый вариант
    if (!Am_Lite::getInstance()->isUserActive()){
        echo "<h4 class=\"alert\">Пользователь без активной подписки</h4>";
    }  
  
$offset=@$_GET['offset'];
  
        if (!isset($offset)){
                $recordoffset=0;
        }else{
                //calc record offset
                $recordoffset=$offset*PERPAGE;
        }

 //убираем полнотекстовый поиск
//$type = $_GET['type'];
$order = mysql_real_escape_string($_REQUEST['order']);
$intitle = (int)$_REQUEST['checktitle'];
$type = 'or';
//выпиливаем поиск по категориям
//$cat = (int)$_GET['cat'];
$cat=0;
$search = $_GET['search'];
$filtered = trim($search); 
$filtered = mysql_real_escape_string($filtered); 
if ($filtered=="") exit;

IF (USE_SPHINX && !$intitle):
    $sphinx_query = goUseSphinx($_GET['search'], $recordoffset, PERPAGE);
    $result = $sphinx_query['result'];
    $totalrecords = $sphinx_query['count'];
ELSE:
echo "WITHOUT SPHINX";


?>
    <h3  class="text-info">Search result for &nbsp;<spans style="color:black;"><?= @$search ?></span></h3>
    
 <?php  

 $sqlhead = "SELECT p.ID, p.post_content, p.post_title, p.prem, p.words, c.cat_name, p.post_date ";

    if ($type=='or')
    {
        //поиск по отдельным словам
       
        
        $querywords = preg_replace("/,/","",$filtered); 
        $querywords = preg_replace("/ +/",",",$querywords); 
        $querywords = preg_replace("/\?/","",$querywords); 
        $querywords = preg_replace("/\(/","",$querywords); 
        $querywords = preg_replace("/\)/","",$querywords); 
        $querywords = preg_replace("/\./","",$querywords); 
        $querywords = preg_replace("/,/","%','%",$querywords); 
        $querywords = preg_replace("/^/","'%",$querywords); 
        $querywords = preg_replace("/$/","%'",$querywords); 
        
               // echo $querywords;

                $eachword = explode(",", $querywords); 
             if ($intitle){
                 //ищем по title
                 $sql = "FROM `posts` as p 
                        LEFT JOIN `relations` AS r ON p.ID = r.post_id
                        LEFT JOIN `category` AS c ON r.cat_id = c.ID
                        WHERE `post_title` LIKE ";
                 
             }else{
                $sql = "FROM `posts` as p 
                        LEFT JOIN `relations` AS r ON p.ID = r.post_id
                        LEFT JOIN `category` AS c ON r.cat_id = c.ID
                        WHERE `post_content` LIKE ";
             }
             
                $size = count($eachword);
             

            for ($c=0; $c<$size; $c++){

                if ($c==$size-1){
                        $sql .= $eachword[$c];
                }else{
                    if ($intitle){
                        $sql .= $eachword[$c]." OR `post_title` LIKE ";
                         }else{
                            $sql .= $eachword[$c]." OR `post_content` LIKE ";}
                }

            }
            
            
           
       
       }
       
        
    else{
      //full-text релятивный поиск  
        
        $sql = "FROM `posts` AS p
                LEFT JOIN `relations` AS r ON p.ID = r.post_id
                LEFT JOIN `category` AS c ON r.cat_id = c.ID
                WHERE MATCH (post_content) AGAINST ('$filtered')";
        
    }
    
//********************************************************************************************
    
    if ($cat>0){
        $sql .=" AND c.ID='$cat'";
    }
    
        $totalrecords = getCol($sql);
        $sql_bezlimit = $sqlhead.$sql;
        getAllId($sql_bezlimit);
        
    if ($order){
        $sql .= " ORDER BY p.".$order;
    }
        // для пагинации
        $sql .= " LIMIT $recordoffset, ".(int)PERPAGE;
        
        
    
 $sql = $sqlhead.$sql;
 //   echo $sql;
    $result = mysql_query($sql) or die('Error, insert query failed');
        //$totalrecords = mysql_num_rows($result); // Узнаем количество элементов в выборке
ENDIF;


    $otherparameter = "&amp;cat=$cat&amp;type=$type&amp;search=$search";
  
?>
  <h4><?php echo $totalrecords; ?><span class="text-info">&nbsp;results found&nbsp;</span>
      
      <?php if ($totalrecords>0): ?>
        
      
      <a id ="alltocart" class="btn btn-success" href="#" onclick="addall(); return false;"><i class="icon-shopping-cart icon-white"></i>&nbsp;Add all to cart</a>
  </h4>
      <?php endif; ?>
      

  
    <form action="" method="get">
           <table class="main_table">
               <thead>
               <tr>
               <th><i class="icon-shopping-cart"></i>&nbsp;Cart</th>     
               <th><i class="icon-filter"></i>&nbsp;<a href="<?php echo "?order=post_title".$otherparameter ?>">Title</a></th>
               <th><i class="icon-filter"></i>&nbsp;<a href="<?php echo "?order=words".$otherparameter ?>"">Words</a></th>
               <th><i class="icon-filter"></i>&nbsp;<a href="<?php echo "?order=post_date".$otherparameter ?>">Date</a></th>
                           
               </tr>
               </thead>
           
                <?php    while ($row = mysql_fetch_assoc($result)) { ?>
                                    <tr><td><a id="<?php echo $row['ID'];?>" href="#" class="addCart"><img class="imgcart" src="../images/cart_add.png">Add</a></td>
                                        
                    <?php    foreach ($row as $key=>$cellValue){ 
                                        if ($key=="ID" or $key=="prem" or $key=="cat_name"  or $key=="post_content") continue;
                                        if ($key=="post_date") {
                                            //выберем дату
                                            $data = explode(" ", $cellValue);
                                            echo "<td>".$data[0]."</td>";
                                            continue;
                                        }
                                        if ($key=="post_title")  {?>
                                        <td class="left-align">
                                           <a href="<?php echo "viewpost.php?id=".$row['ID']."&amp;cat=$cat&amp;type=$type&amp;search=$search";?>"> 
                                              <?php echo excerpt($cellValue); ?>
                                           </a>
                                        </td>
                                         <?php }else { ?>
                                             <td>
                                           
                                              <?php echo excerpt($cellValue); ?>
                                          
                                             </td>
                                             
                                             
                                       <?php       
                                         }
                                                             
                                                                } 
                                        
                                       
                                      ?></tr><?php
                   }   ?>
                                    
           </table>
    </form>
    
<?php  

//**************************************************************************************
              
                
$pagename=basename($_SERVER['PHP_SELF']);

$numpages = ceil($totalrecords/PERPAGE);
//create category parameter
$otherparameter = "&amp;cat=$cat&amp;type=$type&amp;search=$search&amp;order=$order";
//create if needed


  if($numpages>1){
            /*create navigator
            $nav = new pageNavigator($pagename, $totalrecords, PERPAGE, 
                    $recordoffset, 4, $otherparameter);
             
             */
            $nav = pageNavigator::getInstance($pagename, $totalrecords, PERPAGE, $recordoffset, 5, $otherparameter);
            
            echo $nav->getNavigator();
            
                }
                

//***************************************************************************************


}
//********************************Добавить все в корзину*********************************
if (@$_GET['0']){
        $id = array();
        foreach ($_GET as $key=>$value ){
              $id[] .=(int)$value;
        }

        $cookieid = $_COOKIE['basket'];
        $cookieid  = explode(",", $cookieid);
        $out = array();
        $out = array_merge($id, $cookieid);
        $out = array_unique($out);


        $out = implode("," , $out );
        //print_r($out);
        
        echo '<script>$.cookie("basket","'.$out.'", {path: "/"});
            history.back();
            </script>';
        //$.cookie("basket", basketRet, {path: "/"});
        //setcookie("basket", $out, 0, "/");


}

function getCol($sql){
    
  $result =  mysql_query("SELECT count(*) as count ".$sql);
    
  $rows = mysql_fetch_assoc($result);
  
  return (int)$rows['count'];
    
    
}

function getAllId($sql){
    
   $result =  mysql_query($sql); 

   $allid = array();
   
        while ($rowid = mysql_fetch_assoc($result)) {
            $allid[] .= $rowid['ID'];
        }
   // return http_build_query($allid);
    ?>
    <script>

  

 //********************add all to cart ***********************************
    function addall(){
       // var params = $(this).attr('href').split('?');
     //   alert("this.search");
        $.ajax({  
				type: "POST",  
				url: "downloadall.php",  
				data: { str: "<?php echo http_build_query($allid); ?>" },
				success: function(theResponse) {
                                       start();
                                }  
			}); 
        
     
        return false;
    };
 
 
    </script>
    
    
    <?php
        
}



function getCat(){
  
    $cat = array();
    $sql = "SELECT * FROM `category`";
    $result = mysql_query($sql); 
    $ret.= "<option selected value='0'>ALL</option>";
    
        while ($rows = mysql_fetch_assoc($result)){
           $ret.= "<option value=".$rows['ID'].">".$rows['cat_name']."</option>";
            
        }
        
        return $ret;
 
}

//-----------------------SphinxClient------------------------------
function goUseSphinx($search1, $offset, $perpage){
    /*
     SELECT p.ID, p.post_content, p.post_title, p.prem, p.words, c.cat_name, p.post_date 
     FROM `posts` as p 
     LEFT JOIN `relations` AS r ON p.ID = r.post_id 
     LEFT JOIN `category` AS c ON r.cat_id = c.ID 
     WHERE `post_content` LIKE '%bill%' LIMIT 0, 25 
     */
  $search = mysql_real_escape_string($search1);
  $sphinx_ret = array();
    
    include_once '../lib/sphinx/sphinxapi.php';

  $cl = new SphinxClient();
  $cl->SetServer( "localhost");
  $cl->SetMatchMode( SPH_MATCH_EXTENDED  );
  //$cl->SetFilter( 'post_content', array( 3 ) );

  $result = $cl->Query( $search , 'src1' );
//1 запрос на кол-во записей
  if ( $result === false ) {
      echo "Query failed: " . $cl->GetLastError() . ".\n";
  }
  else {
      if ( $cl->GetLastWarning() ) {
          echo "WARNING: " . $cl->GetLastWarning() . "
";
      }

      if ( ! empty($result["matches"]) ) {
 
         // return getQueryForSphinxRes($result["matches"]);
          
         // foreach ( $result["matches"] as $doc => $docinfo ) {
              
               // echo "---:$doc:\n";
               // print_r($docinfo);
         //}
     
         $sphinx_ret['count'] = count($result['matches']);

      }
  }
  
 //2 запрос
 $cl->SetLimits($offset, $perpage);
 $result = $cl->Query( $search , 'src1' ); 
  
  if ( $result === false ) {
      echo "Query failed: " . $cl->GetLastError() . ".\n";
  }
  else {
      if ( $cl->GetLastWarning() ) {
          echo "WARNING: " . $cl->GetLastWarning() . "
";
      }

      if ( ! empty($result["matches"]) ) {
 
         $sphinx_ret['result'] =  getQueryForSphinxRes($result["matches"]);
          
         // foreach ( $result["matches"] as $doc => $docinfo ) {
              
               // echo "---:$doc:\n";
               // print_r($docinfo);
         //}
         // echo "<pre>";
         // print_r( $result );
         // echo "----".count($result['matches']);
         // echo "</pre>";
      }
  }
  
  return $sphinx_ret;
  
}


function getQueryForSphinxRes($matches){
    
   foreach ( $matches as $id => $docinfo ) { 
     $ids .= $id.",";
     
 }
 
 $ids = substr($ids, 0, strrpos($ids, ","));
 
    $sql = "SELECT * FROM forSphinx WHERE ID IN ($ids)";
    $result =  mysql_query($sql);
        
    return $result;
    
}

function getQueryForSphinx($matches){
    ?>
    
    <table class="main_table">
               <thead>
               <tr>
               <th><i class="icon-shopping-cart"></i>&nbsp;Cart</th>     
               <th><i class="icon-filter"></i>&nbsp;<a href="<?php echo "?order=post_title".$otherparameter ?>">Title</a></th>
               <th><i class="icon-filter"></i>&nbsp;<a href="<?php echo "?order=words".$otherparameter ?>"">Words</a></th>
               <th><i class="icon-filter"></i>&nbsp;<a href="<?php echo "?order=post_date".$otherparameter ?>">Date</a></th>
                           
               </tr>
               </thead>
    
 <?php   
 foreach ( $matches as $id => $docinfo ) { 
     $ids .= $id.",";
     
 }
 
 $ids = substr($ids, 0, strrpos($ids, ","));
 
    $sql = "SELECT * FROM forSphinx WHERE ID IN ($ids)";
    $result=  mysql_query($sql);
    ?>
    
    
    
           
                <?php    while ($row = mysql_fetch_assoc($result)) { ?>
                                    <tr><td><a id="<?php echo $row['ID'];?>" href="#" class="addCart"><img class="imgcart" src="../images/cart_add.png">Add</a></td>
                                        
                    <?php    foreach ($row as $key=>$cellValue){ 
                                        if ($key=="ID" or $key=="prem" or $key=="cat_name"  or $key=="post_content") continue;
                                        if ($key=="post_date") {
                                            //выберем дату
                                            $data = explode(" ", $cellValue);
                                            echo "<td>".$data[0]."</td>";
                                            continue;
                                        }
                                        if ($key=="post_title")  {?>
                                        <td class="left-align">
                                           <a href="<?php echo "viewpost.php?id=".$row['ID']."&amp;cat=$cat&amp;type=$type&amp;search=$search";?>"> 
                                              <?php echo excerpt($cellValue); ?>
                                           </a>
                                        </td>
                                         <?php }else { ?>
                                             <td>
                                           
                                              <?php echo excerpt($cellValue); ?>
                                          
                                             </td>
                                             
                                             
                                       <?php       
                                         }
                                                             
                                                                } 
                                        
                                       
                                      ?></tr><?php
                   }   ?>
                                    
         
       </table>                              
 <?php
}


?>
<?php  include_once 'footer.php'; ?>